<template>
  <div class="video-player-page">
    <!-- 顶部导航栏 -->
    <div class="top-navbar">
      <div class="navbar-container">
        <router-link :to="`/learning/course/${courseId}`" class="back-button">
          <svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor">
            <path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20v-2z"/>
          </svg>
          返回课程
        </router-link>
        
        <div class="video-title-nav">{{ video?.title }}</div>
        
        <div class="user-info">
          <img :src="getAvatarUrl(userInfo.avatar)" class="user-avatar" alt="头像" />
        </div>
      </div>
    </div>

    <!-- 主内容 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>

    <div v-else-if="video" class="main-content">
      <!-- 视频播放区 -->
      <div class="video-container">
        <!-- 权限提示遮罩 -->
        <div v-if="showAccessPrompt" class="access-prompt-overlay">
          <div class="prompt-content">
            <div class="prompt-icon">🔒</div>
            <h2 class="prompt-title">{{ accessPromptTitle }}</h2>
            <p class="prompt-message">{{ accessPromptMessage }}</p>
            <div class="prompt-actions">
              <button v-if="video.accessType === 'course'" @click="handlePurchaseCourse" class="btn-primary-large">
                💳 购买课程
              </button>
              <button v-if="video.accessType === 'vip'" @click="handleUpgradeVip" class="btn-primary-large">
                👑 开通会员
              </button>
              <button @click="handleBackToCourse" class="btn-secondary-large">
                返回课程
              </button>
            </div>
          </div>
        </div>
        
        <video 
          ref="videoPlayer"
          :src="video.videoUrl"
          controls
          controlsList="nodownload"
          @timeupdate="handleTimeUpdate"
          @loadedmetadata="handleLoadedMetadata"
          @ended="handleVideoEnded"
        >
          您的浏览器不支持视频播放。
        </video>
      </div>

      <!-- 视频信息和导航 -->
      <div class="content-wrapper">
        <div class="video-info-section">
          <h1 class="video-title">{{ video.title }}</h1>
          <p v-if="video.description" class="video-desc">{{ video.description }}</p>
          
          <div class="video-meta">
            <span class="meta-item">
              时长：{{ formatDuration(video.duration) }}
            </span>
            <span v-if="video.progress > 0" class="meta-item">
              已学习：{{ video.progress }}%
            </span>
          </div>
          
          <!-- 上一个/下一个视频 -->
          <div class="video-navigation">
            <button 
              v-if="video.previousVideo" 
              @click="playVideo(video.previousVideo.id)"
              class="nav-btn prev-btn"
            >
              <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
              </svg>
              上一个：{{ video.previousVideo.title }}
            </button>
            
            <button 
              v-if="video.nextVideo" 
              @click="playVideo(video.nextVideo.id)"
              class="nav-btn next-btn"
            >
              下一个：{{ video.nextVideo.title }}
              <svg viewBox="0 0 24 24" width="16" height="16" fill="currentColor">
                <path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/>
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { getVideoDetail, recordLearningProgress } from '../api/learning'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

const userInfo = computed(() => userStore.userInfo)
const videoId = ref(route.params.videoId)

const loading = ref(false)
const video = ref(null)
const courseId = ref(null)
const videoPlayer = ref(null)

const currentTime = ref(0)
const duration = ref(0)
const saveProgressTimer = ref(null)

// 权限控制
const showAccessPrompt = ref(false)
const accessPromptTitle = ref('')
const accessPromptMessage = ref('')
const hasAccess = ref(false)
const maxWatchTime = ref(0)  // 最大可观看时长（秒）

function getAvatarUrl(avatar) {
  if (!avatar) return 'https://via.placeholder.com/32'
  if (avatar.startsWith('http')) return avatar
  return `${import.meta.env.VITE_API_BASE_URL || ''}${avatar}`
}

function formatDuration(seconds) {
  if (!seconds) return '00:00'
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return `${String(mins).padStart(2, '0')}:${String(secs).padStart(2, '0')}`
}

function handleLoadedMetadata() {
  if (videoPlayer.value) {
    duration.value = Math.floor(videoPlayer.value.duration)
    
    // 检查权限并设置最大观看时长
    checkVideoAccess()
    
    // 恢复上次观看位置
    if (hasAccess.value && video.value.watchDuration > 0 && video.value.watchDuration < duration.value) {
      videoPlayer.value.currentTime = video.value.watchDuration
    }
  }
}

function handleTimeUpdate() {
  if (videoPlayer.value) {
    currentTime.value = Math.floor(videoPlayer.value.currentTime)
    
    // 如果是试看，检查是否超过试看时长
    if (!hasAccess.value && maxWatchTime.value > 0 && currentTime.value >= maxWatchTime.value) {
      videoPlayer.value.pause()
      showAccessPrompt.value = true
    }
  }
}

// 检查视频访问权限
function checkVideoAccess() {
  if (!video.value) return
  
  const accessType = video.value.accessType || 'free'
  
  switch (accessType) {
    case 'free':
      // 免费视频，完全访问
      hasAccess.value = true
      maxWatchTime.value = 0
      showAccessPrompt.value = false
      break
      
    case 'preview':
      // 试看视频，限制时长
      hasAccess.value = false
      maxWatchTime.value = video.value.previewDuration || 0
      showAccessPrompt.value = false
      
      if (maxWatchTime.value > 0) {
        accessPromptTitle.value = '试看已结束'
        accessPromptMessage.value = `您已观看了 ${formatDuration(maxWatchTime.value)} 的试看内容，购买课程可继续观看完整视频`
      }
      break
      
    case 'course':
      // 需要购买课程
      const hasPurchased = video.value.hasPurchased || false
      hasAccess.value = hasPurchased
      maxWatchTime.value = 0
      
      if (!hasPurchased) {
        showAccessPrompt.value = true
        accessPromptTitle.value = '需要购买课程'
        accessPromptMessage.value = '此视频需要购买课程后才能观看'
        
        // 暂停视频
        if (videoPlayer.value) {
          videoPlayer.value.pause()
        }
      }
      break
      
    case 'vip':
      // 需要会员
      const isVip = video.value.isVip || false
      hasAccess.value = isVip
      maxWatchTime.value = 0
      
      if (!isVip) {
        showAccessPrompt.value = true
        accessPromptTitle.value = '仅限会员观看'
        accessPromptMessage.value = '此视频仅限会员观看，开通会员享受更多特权'
        
        // 暂停视频
        if (videoPlayer.value) {
          videoPlayer.value.pause()
        }
      }
      break
  }
  
  console.log('🔒 权限检查:', {
    accessType,
    hasAccess: hasAccess.value,
    maxWatchTime: maxWatchTime.value,
    showPrompt: showAccessPrompt.value
  })
}

// 处理购买课程
function handlePurchaseCourse() {
  alert('购买功能开发中，敬请期待！')
  // TODO: 跳转到课程购买页面
  // router.push(`/purchase/course/${courseId.value}`)
}

// 处理升级会员
function handleUpgradeVip() {
  alert('会员升级功能开发中，敬请期待！')
  // TODO: 跳转到会员购买页面
  // router.push('/vip')
}

// 返回课程
function handleBackToCourse() {
  if (courseId.value) {
    router.push(`/learning/course/${courseId.value}`)
  } else {
    router.push('/learning')
  }
}

function handleVideoEnded() {
  // 视频播放结束，自动跳转到下一个视频
  if (video.value.nextVideo) {
    setTimeout(() => {
      playVideo(video.value.nextVideo.id)
    }, 2000)
  }
}

function playVideo(newVideoId) {
  router.push(`/learning/video/${newVideoId}`)
  videoId.value = newVideoId
  loadVideoDetail()
}

async function saveProgress() {
  if (!video.value || !duration.value) return
  
  try {
    const completed = currentTime.value >= duration.value * 0.9
    
    await recordLearningProgress({
      videoId: video.value.id,
      watchDuration: currentTime.value,
      totalDuration: duration.value,
      completed: completed
    })
    
    console.log('✅ 学习进度已保存:', {
      currentTime: currentTime.value,
      duration: duration.value,
      progress: Math.floor((currentTime.value / duration.value) * 100),
      completed
    })
  } catch (error) {
    console.error('❌ 保存进度失败:', error)
  }
}

function startSaveProgress() {
  // 每15秒保存一次进度
  saveProgressTimer.value = setInterval(() => {
    saveProgress()
  }, 15000)
}

function stopSaveProgress() {
  if (saveProgressTimer.value) {
    clearInterval(saveProgressTimer.value)
    saveProgressTimer.value = null
  }
}

async function loadVideoDetail() {
  loading.value = true
  try {
    const res = await getVideoDetail(videoId.value)
    console.log('✅ 视频详情:', res)
    
    if (res.code === 200) {
      video.value = res.data
      courseId.value = res.data.courseId
    }
  } catch (error) {
    console.error('❌ 加载视频详情失败:', error)
    alert('加载失败：' + error.message)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  loadVideoDetail()
  startSaveProgress()
  
  // 页面关闭前保存进度
  window.addEventListener('beforeunload', saveProgress)
})

onUnmounted(() => {
  stopSaveProgress()
  saveProgress()
  window.removeEventListener('beforeunload', saveProgress)
})
</script>

<style scoped lang="scss">
.video-player-page {
  min-height: 100vh;
  background: #000;
}

// 顶部导航栏
.top-navbar {
  background: rgba(0, 0, 0, 0.8);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  position: sticky;
  top: 0;
  z-index: 100;
  
  .navbar-container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 0 24px;
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  
  .back-button {
    display: flex;
    align-items: center;
    gap: 6px;
    color: #fff;
    text-decoration: none;
    padding: 8px 16px;
    border-radius: 6px;
    transition: background 0.2s;
    
    &:hover {
      background: rgba(255, 255, 255, 0.1);
    }
  }
  
  .video-title-nav {
    flex: 1;
    text-align: center;
    color: #fff;
    font-size: 16px;
    font-weight: 600;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    padding: 0 24px;
  }
  
  .user-info {
    .user-avatar {
      width: 32px;
      height: 32px;
      border-radius: 50%;
      object-fit: cover;
    }
  }
}

// 加载状态
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 400px;
  
  .loading-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid rgba(255, 255, 255, 0.2);
    border-top: 3px solid #667eea;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
  
  p {
    margin-top: 16px;
    color: #fff;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 主内容
.main-content {
  max-width: 1400px;
  margin: 0 auto;
}

// 视频容器
.video-container {
  width: 100%;
  max-height: calc(100vh - 56px - 200px);
  background: #000;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  
  video {
    width: 100%;
    max-height: calc(100vh - 56px - 200px);
    outline: none;
  }
  
  // 权限提示遮罩
  .access-prompt-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.95);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10;
    
    .prompt-content {
      text-align: center;
      padding: 40px;
      max-width: 500px;
      
      .prompt-icon {
        font-size: 64px;
        margin-bottom: 20px;
      }
      
      .prompt-title {
        font-size: 28px;
        font-weight: 700;
        color: #fff;
        margin: 0 0 12px 0;
      }
      
      .prompt-message {
        font-size: 16px;
        color: #ccc;
        line-height: 1.6;
        margin-bottom: 32px;
      }
      
      .prompt-actions {
        display: flex;
        flex-direction: column;
        gap: 12px;
        
        .btn-primary-large,
        .btn-secondary-large {
          width: 100%;
          padding: 14px 24px;
          border: none;
          border-radius: 8px;
          font-size: 16px;
          font-weight: 600;
          cursor: pointer;
          transition: all 0.3s;
        }
        
        .btn-primary-large {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
          color: white;
          
          &:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
          }
        }
        
        .btn-secondary-large {
          background: rgba(255, 255, 255, 0.1);
          color: #fff;
          border: 1px solid rgba(255, 255, 255, 0.3);
          
          &:hover {
            background: rgba(255, 255, 255, 0.2);
          }
        }
      }
    }
  }
}

// 内容包装器
.content-wrapper {
  background: #f8f9fa;
  padding: 24px;
}

.video-info-section {
  max-width: 1200px;
  margin: 0 auto;
  background: white;
  border-radius: 12px;
  padding: 24px;
  
  .video-title {
    font-size: 24px;
    font-weight: 700;
    color: #24292f;
    margin: 0 0 12px 0;
  }
  
  .video-desc {
    font-size: 15px;
    color: #57606a;
    line-height: 1.6;
    margin-bottom: 16px;
  }
  
  .video-meta {
    display: flex;
    gap: 16px;
    margin-bottom: 24px;
    padding-bottom: 24px;
    border-bottom: 1px solid #d0d7de;
    
    .meta-item {
      font-size: 14px;
      color: #57606a;
    }
  }
  
  .video-navigation {
    display: flex;
    justify-content: space-between;
    gap: 12px;
    
    .nav-btn {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      padding: 12px 20px;
      background: white;
      border: 1px solid #d0d7de;
      border-radius: 8px;
      color: #24292f;
      font-size: 14px;
      cursor: pointer;
      transition: all 0.2s;
      
      &:hover {
        background: #f6f8fa;
        border-color: #667eea;
        color: #667eea;
      }
      
      &.prev-btn {
        justify-content: flex-start;
      }
      
      &.next-btn {
        justify-content: flex-end;
      }
    }
  }
}

// 响应式
@media (max-width: 768px) {
  .video-container {
    max-height: 50vh;
    
    video {
      max-height: 50vh;
    }
  }
  
  .video-title-nav {
    display: none;
  }
  
  .video-navigation {
    flex-direction: column;
    
    .nav-btn {
      &.prev-btn, &.next-btn {
        justify-content: center;
      }
    }
  }
}
</style>

